package cn.zyx.basic.conllection;

import cn.zyx.basic.util.AjaxResult;
import cn.zyx.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 上传文件统一接口
 *  上传接口
 *  删除接口
 *  修改 = 删除 + 上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {


    /**
     * 上传接口
     * 使用@RequestPart声明，可以直接完成空校验
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            // 获取文件名
            String filename = file.getOriginalFilename();
            // 获取文件的扩展名
            String extName = filename.substring(filename.lastIndexOf(".") + 1);

            // System.out.println("filename==="+filename);
            // System.out.println("extName==="+extName);

            String path = FastDfsUtil.upload(file.getBytes(), extName);
            // path就是 -- /组名/路径
            return AjaxResult.me().setResultObj(path); // /group1/M00/00/76/rBEAA2BU2baAQeIsAABDzO5Q3SE541.jpg
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败!"+e.getMessage());
        }
    }

    /**
     * 删除接口
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy

             // System.out.println("pathTmp ====="+pathTmp);
            // System.out.println("groupName ====="+groupName);
            // System.out.println("remotePath ====="+remotePath);

            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败!"+e.getMessage());
        }
    }
}
